package activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author lishaojun
 * @create 2019-07-08-下午 5:31
 */
public class JmsConsumer_Topic {
    public static final String ACTIVEMQ_URL = "tcp://106.13.85.181:61616";
    public static final String TOPIC_NAME = "topic-atguigu";
    public static void main(String args[]) throws Exception{
        System.out.println("我是3号消费者");
        //1.创建连接工厂,按照地址给定的用户名密码
        ActiveMQConnectionFactory activeMQConnectionFactory=new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂获得连接
        Connection connection=activeMQConnectionFactory.createConnection();
        connection.start();
        //3.创建会话,方法两个参数一个是事务，一个是签收
        Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //4.创建目的地，具体是队列或者是主题
        Topic topic=session.createTopic(TOPIC_NAME);
        //5.创建消息的消费者
        MessageConsumer messageConsumer=session.createConsumer(topic);

        //接收方式2 使用监听器
        messageConsumer.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {

                if (null!=message&& message instanceof TextMessage){
                    TextMessage textMessage= (TextMessage) message;

                    try {
                        System.out.println(textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.in.read();//不写这句话，会出现消费者还没消费，资源就被关闭了
        messageConsumer.close();
        session.close();
        connection.close();
        System.out.println("主题接收完毕");
    }
}
